package org.springframework.security.oauth2.provider.code;

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

/**
 * Base implementation for authorization code services that generates a random-value authorization code.
 *
 * @author Ryan Heaton
 * @author Dave Syer
 */
public abstract class RandomValueAuthorizationCodeServices implements AuthorizationCodeServices {

	/*xxx: 随机数生成器*/
	private RandomValueStringGenerator generator = new RandomValueStringGenerator();

	/*xxx: 存储授权码*/
	protected abstract void store(String code, OAuth2Authentication authentication);

	/*xxx: 移除授权码*/
	protected abstract OAuth2Authentication remove(String code);

	/*xxx: 创建授权码，默认情况下，是根据随机数生成的*/
	public String createAuthorizationCode(OAuth2Authentication authentication) {
		String code = generator.generate();
		/*xxx: 对于生成的授权码，需要对其进行保存*/
		/*xxx: 保存授权码，默认情况下，支持两种: inMemory,inJdbc*/
		store(code, authentication);
		return code;
	}

	public OAuth2Authentication consumeAuthorizationCode(String code)
			throws InvalidGrantException {
		/*xxx: 消费授权码时，需要对其移除*/
		OAuth2Authentication auth = this.remove(code);
		if (auth == null) {
			throw new InvalidGrantException("Invalid authorization code: " + code);
		}
		return auth;
	}

}
